package com.bee.app.plugin;

import java.lang.reflect.Method;
import java.util.List;

import com.bee.app.tool.ClassSearcher;
import com.bee.app.util.StringKit;
import com.jfinal.config.Routes;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Logger;

/**
 * 自动扫描包配置路由插件
 * 
 * @author liuzy
 * @version 2015年7月2日
 */
public class LoadRoutes {

	private Logger log = Logger.getLogger(LoadRoutes.class);

	private Routes me;

	public LoadRoutes(Routes me) {
		this.me = me;
	}

	public void scan() {
		String path = PropKit.get("controller.path");
		if (StringKit.isNullOrEmpty(path)) {
			log.warn("controller.path没有设置");
			path = "/";
		}
		List<Class<? extends Controller>> classes = ClassSearcher.search(Controller.class, path);
		for (Class<? extends Controller> clazz : classes) {
			if (clazz.isAnnotationPresent(com.bee.app.jfinal.Controller.class)) {
				String key = clazz.getAnnotation(com.bee.app.jfinal.Controller.class).value();
				me.add(key, clazz);
				key = "/".equals(key) ? "" : key;
				Method[] methods = clazz.getDeclaredMethods();
				for (Method method : methods) {
					log.debug("Mapped route:[" + key + "/" + method.getName() + "] " + clazz.getName());
				}
			}
		}
	}

}
